#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'wshu'
"""
    ***********************************
    *  @filename : nodeconf.py
    *  @Author : wshu
    *  @CodeDate : 2020/3/9 12:36
    *  @Software : PyCharm
    ***********************************
"""
import os
import sys
import traceback
from uuid import uuid4
import json as serializer

def get_old_id(config_file='/etc/node.conf'):
	""" 从老版本配置文件里获取 id """
	try:
		import yaml

		conf = yaml.load( open(config_file, 'r') )
		nid = conf['id']
	except:
		nid =  None

	return nid


class CNodeConf(dict):
    """
        节点 配置 对象
    """

    def __init__(self, conf_file=None):
        """ init """
        if not conf_file:
            conf_file = os.path.join(os.getenv('DATA_PATH', '/var/data'),
                                     'node.conf')

        self.conf_file = conf_file
        self._init()

    def _init(self):
        """ 初始化 """
        self._load()
        if self.set_id() and not self.save():
            raise Exception('Failed to init node ID')

    def _load(self):
        """ 加载配置信息 """
        try:
            conf = serializer.load(open(self.conf_file, 'r'))
            self.update(conf)
        except Exception:
            pass

    def set_id(self, force=False):
        """ 设置 Node ID
        force: 是否强制更新

        如果改变了 id 则返回 True；否则返回 False
        """
        if force:
            self['id'] = uuid4().hex
            return True
        elif 'id' not in self:
            nid = get_old_id()
            self['id'] = nid if nid else uuid4().hex
            return True
        else:
            return False

    def save(self):
        """ 保存配置信息 """
        try:
            serializer.dump(self, open(self.conf_file, 'w'), indent=1)
            return True
        except:
            traceback.print_exc()
            return False

    def dump(self, dumpfile=sys.stdout):
        """ 显示配置信息 """
        try:
            serializer.dump(self, dumpfile, indent=1)
            print(dumpfile, file=sys.stderr)
        except:
            traceback.print_exc()